package com.lez.flowpractice2.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.lez.common.LocalEventBus
import com.lez.flowpractice2.R
import com.lez.flowpractice2.databinding.FragmentSharedFlowBinding
import com.lez.flowpractice2.viewmodel.SharedFlowViewModel
import kotlinx.coroutines.flow.collect

/**
 * SharedFlow会向从其中收集值的所有使用方发出数据
 */
class SharedFlowFragment : Fragment() {

    private val mBinding : FragmentSharedFlowBinding by lazy {
        FragmentSharedFlowBinding.inflate(layoutInflater)
    }
    private val sharedFlowViewModel by viewModels<SharedFlowViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mBinding.apply {

            startBtn.setOnClickListener {
                sharedFlowViewModel.startRefresh()
            }
            stopBtn.setOnClickListener {
                sharedFlowViewModel.stopRefresh()
            }

        }

        lifecycleScope.launchWhenCreated {

            LocalEventBus.events.collect {
                mBinding.oneTV.text = "${it.timestamp}"
                mBinding.twoTV.text = "${it.timestamp}"
                mBinding.threeTV.text = "${it.timestamp}"
            }

        }
    }
}